/**
 * 输入框
 */

import { useState, FormEvent } from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useConversation } from '@/context/conversationContext';
import { useSocket } from '@/context/socketContext';

export default function MessageInput() {
  const [message, setMessage] = useState('');
  const { currentConversation } = useConversation();
  const socket = useSocket();

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    if (!message.trim() || !currentConversation) return;
    // @ts-ignore
    const target = currentConversation.type === 'private' ? currentConversation.participants[0].id : currentConversation.id;

    const messageData = {
      content: message.trim(),
      conversationId: currentConversation.id,
      type: currentConversation.type,
      to: target,
    };

    try {
      // @ts-ignore
      // 发送消息到服务器
      socket?.emit('message', messageData);
      // 清空输入框
      setMessage('');
    } catch (error) {
      console.error('发送消息失败:', error);
    }
  };

  return (
    <form className="flex gap-2" onSubmit={handleSubmit}>
      <Input 
        className="flex-1" 
        placeholder="输入消息..." 
        value={message}
        onChange={(e) => setMessage(e.target.value)}
      />
      <Button type="submit" disabled={!message.trim()}>发送</Button>
    </form>
  );
}
